// Fill out your copyright notice in the Description page of Project Settings.


#include "FireBaseCpp.h"
#include "PlayerBaseCpp.h"
#include "GameModeBaseCpp.h"

AFireBaseCpp::AFireBaseCpp()
{
	PrimaryActorTick.bCanEverTick = true;
	Lock = true;
	SpriteComponent->SetLooping(false);
	Tags.Add(FName("Fire"));
}

void AFireBaseCpp::BeginPlay()
{
	Super::BeginPlay();
	FScriptDelegate FireOverlapDelegate;
	FireOverlapDelegate.BindUFunction(this, "OnFireOverlapStart");
	BoxCollider->OnComponentBeginOverlap.Add(FireOverlapDelegate);
	FScriptDelegate FireEndOverlapDelegate;
	FireEndOverlapDelegate.BindUFunction(this, "OnFireOverlapEnd");
	BoxCollider->OnComponentEndOverlap.Add(FireEndOverlapDelegate);
	FScriptDelegate EndPlayDelegate;
	EndPlayDelegate.BindUFunction(this, "EndPlayCallback");
	SpriteComponent->OnFinishedPlaying.Add(EndPlayDelegate);

	AGameModeBaseCpp* CurrentGameMode = Cast<AGameModeBaseCpp>(UGameplayStatics::GetGameMode(GetWorld()));
	float DamageValue = 0.0f;
	CurrentGameMode->GetPawnDamageMap(EPawnType::E_Demon, EAttackMode::E_Attack1, DamageValue);
	SetWeaponDamage(DamageValue);
}

void AFireBaseCpp::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	const auto F = SpriteComponent->GetPlaybackPositionInFrames();
	if ((F == 1 || F == 2 || F == 3) && Players.Num() != 0)
	{
		for (APlayerBaseCpp* P : Players)
		{
			if (P == nullptr)
			{
				break;
			}
			UGameplayStatics::ApplyDamage(P, WeaponDamage * DeltaSeconds, nullptr, this, nullptr);
		}
	}
}

void AFireBaseCpp::OnFireOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
	if (OtherActor && OtherActor->ActorHasTag(FName("Player")))
	{
		APlayerBaseCpp* P = Cast<APlayerBaseCpp>(OtherActor);
		if (Players.Contains(P))
		{
			Players.Remove(P);
		}
	}
}


void AFireBaseCpp::SetParam()
{
	SetActorHiddenInGame(false);
	BoxCollider->SetActive(true);
	SpriteComponent->SetPlaybackPositionInFrames(0, false);
	SpriteComponent->Play();
}

void AFireBaseCpp::SetLock()
{
	BoxCollider->SetActive(false);
	SetActorHiddenInGame(true);
}

void AFireBaseCpp::OnFireOverlapStart(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor && OtherActor->ActorHasTag(FName("Player")))
	{
		APlayerBaseCpp* Player = Cast<APlayerBaseCpp>(OtherActor);
		Players.Emplace(Player);
	}
}

void AFireBaseCpp::EndPlayCallback()
{
	SetLock();
	AGameModeBaseCpp* CurrentGameMode = Cast<AGameModeBaseCpp>(UGameplayStatics::GetGameMode(GetWorld()));
	CurrentGameMode->TryPutFireObjToPool(this);
}

